//
//  ToisoAppDelegate.m
//  Toiso
//
//  Created by ff xu on 1/7/12.
//  Copyright 2012 codable. All rights reserved.
//

#import "ToisoAppDelegate.h"
#include "bchunk.h"
void bchunk_notify_cb(void* context, int total, int done)
{
    ToisoAppDelegate* app = context;
    [app notify: done withTotal: total];
}
@implementation ToisoAppDelegate
- (void) awakeFromNib
{
    [NSApp setDelegate:self];
}

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
}

- (BOOL)convertWithCue:(NSString *)cue withBin:(NSString *)bin
{
    const char* iso = [[cue stringByReplacingOccurrencesOfString: @".cue" withString: @".iso"] cStringUsingEncoding: NSUTF8StringEncoding];
    const char* argv[] = {"bchunk", [bin cStringUsingEncoding: NSUTF8StringEncoding], [cue cStringUsingEncoding: NSUTF8StringEncoding], iso};
    [message setStringValue: @"Converting.."];
    bchunk_context = self;
    bchunk_notifier = &bchunk_notify_cb;
    BOOL ok = (0 == fake_main(4, argv));
    if (ok) {
        [message setStringValue: @"Success!"];
    } else {
        [message setStringValue: @"Fail!"];
    }
    return ok;
}

- (void)notify:(int)done withTotal:(int)total
{
    NSString* msg = [NSString stringWithFormat: @"Converting: %6d/%6d MB", done, total];
    [message setStringValue: msg];
    NSEvent *event = NULL;
    while ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
                                      untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES]))
        [NSApp sendEvent:event];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
    return YES;
}
@end
